三味猪屋

objc_msgSend 的正确使用姿势

首先需要import objc_msgSend 所在的头文件

1
#import <objc/message.h>

‘objc_msgSend’ 同时在 都有定义,需要进一步了解其异同。

在64位机器上运行‘objc_msgSend’,如果姿势不对,编译器不会提示警告,而是直接crash。

解决办法:

需要将objc_msgSend重新声明成自己想要的参数,如下所示:

1
2
//objc_msgSend(self,selector,@"test");
((void(*)(id, SEL, id))objc_msgSend)(self, selector, @"test");

详情请参照苹果官方文档

1
2
3
4
5
6
Listing 2-14 Using a cast to call the Objective-C message sending functions
- (int) doSomething:(int) x { ... }
- (void) doSomethingElse {
int (*action)(id, SEL, int) = (int (*)(id, SEL, int)) objc_msgSend;
action(self, @selector(doSomething:), 0);
}